<template>
    <div class="exam-management" style="width:80%;height:80%">
        
      <!-- 搜索栏 -->
        <div class="search">
             <!-- 考试名称输入框 -->
            <div class="select-group">
                <label>考试名称 </label>
                <input type="text" v-model="exam.name" placeholder="请输入" style="height: 28px;width:280px"/>
            </div>
        
            <!-- 状态选择 -->
            <div class="select-group">
                <label>状态 </label>
                <select v-model="exam.state" style="height: 28px;width:150px">
                    <option value="1">待开展</option>
                    <option value="2">进行中</option>
                    <option value="3">已结束</option>
                    <option value="4">待批改</option>
                </select>
            </div>
  
            <!-- 时间选择 -->
            <div class="select-group">
                <label> 从 </label>
                <input type="date" v-model="exam.startTime" style="height: 28px;width:150px"/>
                <label> 至 </label>
                <input type="date" v-model="exam.endTime" style="height: 28px;width:150px"/>
            </div>

            <el-button type="primary" plain @click="searchExam('exam')" class="search-button">查询</el-button>
        </div>
     
      <!-- 考试列表 -->
      <div v-if="examList && examList.length > 0">
        <div class="exam-list">
            <div v-for="(item, index) in examList" :key="index" class="exam-item">
              <div class="exam-info" style="width:80%">
                <div class="exam-title">{{ item.name }}</div>
                <span>考试开始时间:{{ item.startTime }}</span>
                <span> 考试结束时间:{{ item.endTime }}</span>
                <span> 时限:{{ item.duration }}分钟</span>
                <span class="remark"> 允许点击“开始考试”倒计时：</span>
                <!-- <div :class="getStatusClass(item.state)" class="exam-status">{{ item.state }}</div> -->
                <div class="remind">
                  考试注意点:
                  <ol>
                    <li>本次考试为线上闭卷考试</li>
                    <li>本次考试不允许提前进入！</li>
                    <li>考试发布一周内可参加答卷</li>
                  </ol>
                </div>                                                                                                                                                                                        
              </div>
              <div class="exam-actions">
                  <div :class="getStatusClass(item.state)" class="exam-status">{{ item.state }}</div><br/><br/><br/>
                  <button v-if="item.state === '待开展'"  @click="editExam(item.id)">发布</button>
                  <button v-if="item.state === '已结束'"  @click="viewExam(item.id)">查看考试</button>
                  <button v-if="item.state === '待批改'"  @click="correctExam(item.id)">批改</button>
              </div>  
            </div>
        </div>

        <!-- 分页组件 -->
        <div class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">&lt;</button>
          <button v-for="page in totalPages" :key="page" @click="goToPage(page)" :class="{ active: page === currentPage }">{{ page }}</button>
          <button @click="nextPage" :disabled="currentPage === totalPages">&gt;</button>
        </div>
      </div>
      
      <div v-else class="noData">
        <img src="@/assets/img/noDataView.png" alt="No Data Found"/>
      </div>
     
    </div>
  </template>
  
  <script setup>
  //import httpInstance from '@/utils/http';
  import { ref, reactive, computed ,onMounted} from 'vue';
  import { formatDate,formatDateToYMD } from '@/utils/dateUtil';
  import { interceptor } from '@/utils/interceptor';
  import { useRouter } from 'vue-router';

  
  onMounted(()=>{
    searchExam();
  })
  
  // 定义一个响应式的 exam 对象用于存储搜索条件
  const exam = reactive({
      name: '',
      state: '',
      startTime: '',
      endTime: '',
      page: 1,
      pageSize: 4,
      teacherId:''
  });
  
  // 当前页码
  const currentPage = ref(1);
  
  // 总记录数，用于计算总页数
  const totalRecords = ref(0);
  
  // 定义 examList 为一个响应式的引用类型，用于存储考试列表数据
  const examList = ref([]);
  
  // 使用计算属性来计算总页数
  const totalPages = computed(() => {
      return Math.ceil(totalRecords.value / exam.pageSize);
  });

  const router = useRouter()

 /*  // 创建一个 Axios 实例
const httpInstance = axios.create({
    baseURL: 'http://localhost:8080', // 替换成你的后端API基础URL
    timeout: 2592000000,
});

// 请求拦截器
httpInstance.interceptors.request.use(config => {
    // 尝试从 localStorage 获取 token
    const token = localStorage.getItem('token'); // 假设你在登录后将token保存在localStorage中
    console.log("token:",token)
    if (token) {
        config.headers['token'] = `${token}`; // 添加 token 请求头
    }
    return config;
}, error => {
    // 请求错误处理
    return Promise.reject(error);
}); */
  
  // 搜索考试的方法
  const searchExam = () => {
      // 更新当前页码到 exam 对象
      exam.page = currentPage.value;
  
      // 清空旧的 exams 数据
      examList.value = [];

     // const formattedStartTime = exam.startTime ? formatDate(new Date(exam.startTime)) : null;
     // const formattedEndTime = exam.endTime ? formatDate(new Date(exam.endTime)) : null;
     // console.log("startTime:",exam.startTime)
      //console.log("formattedStartTime:",formattedStartTime)
  
      const httpInstance = interceptor()

      httpInstance.post("/teacher/exam/page", {
          name: exam.name,
          state: exam.state,
          startTime: exam.startTime,
          endTime: exam.endTime,
          page: exam.page,
          pageSize: exam.pageSize,
          teacherId: localStorage.getItem("user-id")
      }).then((res) => {
        console.log("Exam data:", res.data); // 打印出接收到的数据
          // 假设返回的数据结构包含 records 和 total 字段
          /* exams.value = res.data.records.map(record => ({
              id: record.id,
              name: record.name,
              state: record.state === 1 ? '待开展' : record.state === 2 ? '进行中' : '已结束',
              duration: record.duration,
              startTime: record.startTime,
              endTime: record.endTime,
          }));
          totalRecords.value = res.data.total; // 更新总条目数 
          // */
          if (res.data && res.data.code === 1 && Array.isArray(res.data.data.records)) {
            examList.value = res.data.data.records.map(exam => ({
                id: exam.id,
                name: exam.name,
                state: exam.state === 1 ? '待开展' : exam.state === 2 ? '进行中' : exam.state === 3 ? '已结束' : '待批改',
                duration: exam.duration,
                startTime: formatDateToYMD(exam.startTime),
                endTime: formatDateToYMD(exam.endTime),
                // 其他需要映射的字段...
            }));
            // 使用examList... 
            totalRecords.value = res.data.data.total; // 更新总条目数 */
            //console.log("totalRecords:", totalRecords.value);
            //console.log("Exam List:", examList.value);
         } else {
            console.warn("Invalid response structure or no records found");
        }
      }).catch(error => {
          console.error("查询考试失败:", error);
      });
  
      console.log('查询考试:', exam.state);
  };

  const getStatusClass = (state) =>  {
      switch (state) {
        case '待开展':
          return 'state-pending';
        case '进行中':
          return 'state-in-progress';
        case '已结束':
          return 'state-ended';
        case '待批改':
          return 'state-correcting'
        default:
          return ''; // 或者返回默认样式
      }
    }
  
  // 分页相关的方法
  const prevPage = () => {
      if (currentPage.value > 1) {
          currentPage.value--;
          searchExam();
      }
  };
  
  const nextPage = () => {
      if (currentPage.value < totalPages.value) {
          currentPage.value++;
          searchExam();
      }
  };
  
  const goToPage = (page) => {
      if (page >= 1 && page <= totalPages.value) {
          currentPage.value = page;
          searchExam();
      }
  };
  
  // 编辑发布方法
  const editExam = function(id){
    try{
      console.log('编辑发布:', id);
      const httpInstance = interceptor()
      httpInstance.put(`/teacher/exam/${id}`).then((res)=>{
          console.log(res.data);
          // 可能需要刷新考试列表
          searchExam();
      });
      alert("发布成功！")
    }catch(error){
      console.log('发布失败:',error)
    }
      
  }

  //查看成绩
  const viewExam = (id) => {
    
    console.log("id:",id)
    router.push({
        name:'score',
        params: {examId: id}
    })
  }

  //批改
  const correctExam = (id) => {
    console.log("id:",id)
    router.push({
      name:'correctExam',
      params:{examId: id}
    })
  }
  </script>
  
  <style scoped>
  .noData img{
     max-width:100%;
     height:auto;
     margin-left:-20%;
  }
  
  .exam-management {
    padding: 50px;
    width:90%;
    margin:auto;
  }
  
  .search{
    display: flex;
  }

  .select-group{
    margin-bottom: 10px;
    margin-left: 20px;
    margin-right: 5px;
  }

  .select-group label{
    font-size:20px;
    color: #333;
  }

  .search-button {
    margin-top: 5px;
    margin-left:8px;
    height: 28px;
    font-size:17px;
/*     background-color: #afe1f0; 
    border: none;
   
    color: black;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 25px;
    cursor: pointer;
    border-radius: 8px; */
}

/* .search-exam button:hover {
    background-color: white;
    color: black;
    border: 2px solid  #afe1f0;
} */

.exam-actions{
  display: flex;
  /* justify-content: flex-end; */
  flex-direction: column;  /* 子元素垂直排列 */
  align-items: flex-end;  /* 每个子元素在其所在行内靠右对齐 */
}

.exam-actions button {
  color:rgb(139, 210, 7);
  font-weight:600;
  background-color: rgba(0,0,0,0);
  border: none;
  font-size:17px;
    /* background-color: #4CAF50; 
    border: none;
    color: white;
    padding: 5px 10px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
    border-radius: 8px;
    transition-duration: 0.4s;  */ /* Smooth transition */
}

.exam-actions button:hover {
    background-color: rgba(0,0,0,0);
/*     color: black;
    border: 2px solid #4CAF50; */
}
  
  .exam-list {
    margin-top: 20px;
  }
  
  .exam-item {
    border: 1px solid #ccc;
    padding: 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.3);
    border-radius: 8px;
    height:150px;
  }

  .exam-title{
    font-size: 22px;
    font-weight: bold;
  }

  .remark{
    color:#a29d9d;
  }

  .exam-status {
    font-size: 18px;
    font-weight: 600;
}

.state-pending {
    color:rgb(252, 214, 0);/* 待开展 */
}

.state-in-progress {
    color:#f93e3e; /* 红色，代表进行中 */
    
}

.state-ended {
    color: #a29d9d;/* 代表已结束 */
    
}

.state-correcting{
  color: green; /* 待批改 */
}

.remind{
  font-size:12px;
  color:#878282;
}

.pagination{
  display: flex;
  /* width:100%; */
  justify-content: center;
}
  
  .pagination button {
    margin: 0 5px;
  }
  
  .active {
    background-color: #298df8c9;
    border: none;
    color: white;

  }
  </style>